package com.mrxy.mouse.service;

import com.mrxy.mouse.domain.MyUser;
import com.mrxy.mouse.mapper.UserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * @author 朝花不迟暮
 * @version 1.0
 * @date 2020/11/7 19:42
 */
@Service
public class UserService implements UserDetailsService
{
    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
    {
        MyUser myUser = userMapper.loadUserByUsername(username);
        if (myUser == null)
        {
            throw new UsernameNotFoundException("查无此人！");
        }
        return myUser;
    }

    public boolean register(String username, String password)
    {
        MyUser myUser = userMapper.loadUserByUsername(username);
        if (myUser == null&&!StringUtils.isEmpty(username)&&!StringUtils.isEmpty(password))
        {
            String password1 = passwordEncoder.encode(password);
            log.info("【查看加密后的密码】password1:{}", password1);
            //如果根据用户名没有查到数据，说明可以注册！
            userMapper.registerUser(username, password1, true, true);
            log.info("【用户添加完成】");
            return true;
        }
        log.info("【用户添加失败】");
        return false;
    }
}
